/* 设备详情跳转状态 */
deviceRedirect = true;

var rem = parseInt($('html').css('font-size'));
var hspId = GetQueryString('hospitalId') || '';
if (hspId) {
    localStorage.setItem('hospital_id', hspId);
} else {
    hspId = localStorage.getItem('hospital_id');
}
if (hspId && hspId !== 'null') {
    $('#btn1').hide();
}
$(function(){
    FastClick.attach( document.body );
});

var barMaxWidth = '40px';   // 柱状图柱子最大宽度
var basePath = basePath();
var lang = 'zh';
if ($('#language .language').text().indexOf('English') != -1) {
    lang = 'en';
}

$('#btn1').attr('href', basePath + '/index/page');

window.onresize = function () {
    resizeWindow();
    chart.resize();
};

function changeTime(el, value) {
    if (value / 60 / 24 >= 1) {
        el.html(parseFloat(value / 60 / 24).toFixed(2)).next('span').html(lang === 'zh' ? '天' : 'Day');
    } else if (value / 60 >= 1) {
        el.html(parseFloat(value / 60).toFixed(2)).next('span').html(lang === 'zh' ? '小时' : 'Hr');
    } else {
        el.html(parseFloat(value).toFixed(2)).next('span').html(lang === 'zh' ? '分钟' : 'Min');
    }
}

function min2bigger (value) {
    var json = {};
    value = value || 0;
    if (value / 60 / 24 >= 1) {
        json = {value: fix2(value / 60 / 24),unit: '天'};
    } else if (value / 60 >= 1) {
        json = {value: fix2(value / 60),unit: '小时'};
    } else {
        json = {value: value,unit: '分钟'};
    }
    json.all = json.value + json.unit;
    return json;
}

/* 页面跳转 */
function jumpTo(path) {
    location.href = path;
}

/* 新开页面 */
function winOpen(path) {
    window.open(basePath + path);
}

//轮播
var Swiper = {
    main: $('#swiper'),
    init: function () {
        this.index = 0;
        this.width = this.main.width();
        this.leftBtn = this.main.find('.btn-left');
        this.rightBtn = this.main.find('.btn-right');
        this.btnClick();
    },
    changeChart: function (index) {
        this.index = index;
        this.main.find('.swiper-container').animate({
            marginLeft: index * this.width * (-1)
        }, 500);
        if (index === 0 && currentOption.series[0].type === 'scatter') {
            $('.quadrantContainner').show();
        } else {
            $('.quadrantContainner').hide();
        }
    },
    btnClick: function () {
        var _this = this;
        this.leftBtn.click(function () {
            _this.changeChart(0);
        });
        this.rightBtn.click(function () {
            _this.changeChart(1);
        });
        option_flag = null;
        $('.option').removeClass('active');
    }
};

//封装点击变色方法
function clickChange(el) {
    el.click(function () {
        el.removeClass('active');
        $(this).addClass('active');
    });
}

function clickToggle(el) {
    el.click(function () {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            el.removeClass('active');
            $(this).addClass('active');
        }
    });
}

// 点击多选
function clickActive(el) {
    el.click(function () {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active');
        }
    });
}

/*
* 数字变换动画
* {
*   el: el,  jquery对象
*   newNum: 20, 新的数字
*   fixNum: 2,  保留两位小数
*   totalTime： 1000,   动画时间1000ms
*   interval: 20,
*
* }
* */
function numAnimate(param, fn) {
    param = $.extend({
        el: $(),  // jquery对象
        newNum: 0, // 新的数字
        fixNum: 0,  // 保留两位小数
        unit: '',   // 单位
        totalTime: 1000,   // 动画时间1000ms
        interval: 20   // 间隔时间20s
    }, param);
    var oldNum = parseFloat(param.el.text());
    var count = param.totalTime / param.interval;
    var dValue = (param.newNum - oldNum) / count;
    var flag = 0;
    var timer = setInterval(function () {
        oldNum += dValue;
        param.el.text(oldNum.toFixed(param.fixNum) + param.unit);
        flag++;
        if (flag >= count) {
            param.el.text(param.newNum.toFixed(param.fixNum) + param.unit);
            clearInterval(timer);
            if (typeof fn === 'function') fn();
        }
    }, param.interval);
}
/* 设备情况分析 一行放不下就放两行 */
function resizeLayout() {
    var item = $('p.layout'),
        lineHeight = parseFloat(item.eq(0).css('line-height')),
        flag = false;
    item.each(function () {
        var obj = $(this);
        if (obj.height() > lineHeight) {
            flag = true;
        }
    });
    if (flag) {
        item.addClass('pad');
    } else {
        item.removeClass('pad');
    }
}

//定义一个StringBuffer类
function StringBuffer() {
    this.__strings__ = [];
}

StringBuffer.prototype.append = function (str) {
    this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
    return this.__strings__.join('');
};

//最小值
Array.prototype.min = function (key) {
    var min;
    if (key) {
        min = parseFloat(this[0][key] || 0);
        for (var i = 1; i < this.length; i++) {
            if (parseFloat(this[i][key] || 0) < min) {
                min = parseFloat(this[i][key] || 0);
            }
        }
    } else {
        min = parseFloat(this[0] || 0);
        for (var i = 1; i < this.length; i++) {
            if (parseFloat(this[i] || 0) < min) {
                min = parseFloat(this[i] || 0);
            }
        }
    }
    return min;
};
//最大值
Array.prototype.max = function (key) {
    var max;
    if (key) {
        max = parseFloat(this[0][key] || 0);
        for (var i = 1; i < this.length; i++) {
            if (parseFloat(this[i][key] || 0) > max) {
                max = parseFloat(this[i][key] || 0);
            }
        }
    } else {
        max = parseFloat(this[0] || 0);
        for (var i = 1; i < this.length; i++) {
            if (parseFloat(this[i] || 0) > max) {
                max = parseFloat(this[i] || 0);
            }
        }
    }
    return max;
};
Array.prototype.removeByValue = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
};

Array.prototype.hasValue = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            return true;
        }
    }
    return false;
};



/*
* 根据数组的子JSON的key排序
* 默认倒序排序[{pis:dds},{}]
* 不传key就返回原数组
* */
Array.prototype.sortByKey = function (sorting, key, deep) {
    if (arguments.length > 0 && arguments.length < 4) {
        if (arguments.length === 1) {
            if (typeof sorting === 'string') {
                deep = true;
                key = sorting;
                sorting = 'desc';
            } else {
                console.log('请传入按照什么key排序');
                return;
            }
        } else if (arguments.length === 2) {
            if (typeof sorting === 'string' && (typeof key === 'string')) {
                sorting = (sorting === 'desc' || sorting === 'asc') ? sorting : 'desc';
                deep = true;
            } else if (typeof sorting === 'string' && (typeof key === 'boolean')) {
                deep = key;
                key = sorting;
                sorting = 'desc';
            } else {
                console.log('请传入按照什么key排序');
                return;
            }
        }
    } else {
        console.log('请传入1-3个参数[排序方式(desc|asc),按照什么字段排序,是否排序子数组(默认true)]');
        return;
    }
    for (var i = 0; i < this.length; i++) {
        for (var j = 0; j < this.length - i - 1; j++) {
            var temp;
            if (sorting === 'asc') {
                if (convert(this[j][key]) > convert(this[j + 1][key])) {
                    temp = this[j];
                    this[j] = this[j + 1];
                    this[j + 1] = temp;
                }
            } else {
                if (convert(this[j][key]) < convert(this[j + 1][key])) {
                    temp = this[j];
                    this[j] = this[j + 1];
                    this[j + 1] = temp;
                }
            }
        }
    }
    if (deep) {
        for (var i = 0; i < this.length; i++) {
            if (this[i].list && (typeof this[i].list === 'object')) this[i].list.sortByKey(sorting, key, deep);
        }
    }
    if (this[-1] && this[-1].list && (typeof this[-1].list === 'object')) this[-1].list.sortByKey(sorting, key, deep);
    return this;
};

/*
* 计算JSON数字的总数
* */
Array.prototype.calTotal = function () {
    var keyArr = [];
    var total = {};
    for (var i = 0; i < this.length; i++) {
        for (var key in this[i]) {
            if (!keyArr.hasValue(key)) keyArr.push(key);
        }
        for (var k = 0; k < keyArr.length; k++) {
            if (typeof this[i][keyArr[k]] === 'object' && this[i][keyArr[k]] !== null) {
                total[keyArr[k]] = (total[keyArr[k]] || []).concat(this[i][keyArr[k]]);
            } else {
                total[keyArr[k]] = (parseFloat(total[keyArr[k]]) || 0) + (parseFloat(this[i][keyArr[k]]) || 0);
            }
        }
    }
    this[-1] = total;
    return this;
};
Array.prototype.calc = function (operator, num, fixNum) {
    var keyArr = [];
    if (operator === '/') {
        for (var i = 0; i < this.length; i++) {
            keyArr.push(fixNum ? parseFloat(this[i] / num).toFixed(fixNum) : this[i] / num);
        }
    } else if (operator === '*') {
        for (var i = 0; i < this.length; i++) {
            keyArr.push(fixNum ? parseFloat(this[i] * num).toFixed(fixNum) : this[i] * num);
        }
    } else if (operator === '+') {
        for (var i = 0; i < this.length; i++) {
            keyArr.push(fixNum ? parseFloat(this[i] + num).toFixed(fixNum) : this[i] + num);
        }
    } else if (operator === '-') {
        for (var i = 0; i < this.length; i++) {
            keyArr.push(fixNum ? parseFloat(this[i] - num).toFixed(fixNum) : this[i] - num);
        }
    }
    return keyArr;
};
Array.prototype.getArrayByKey = function (key) {
    var keyArr = [];
    for (var i = 0; i < this.length; i++) {
        keyArr.push(this[i][key]);
    }
    return keyArr;
};

//将字符串转换为数值类型
function parseStringData(data) {
    for (var i = 0; i < data.length; i++) {
        data[i] = parseFloat(data[i]);
    }
}

// 保存两位小数
function fix2(string) {
    return parseFloat(string || 0).toFixed(2);
}

// 保存为整数或者 0
function fix0(string) {
    return parseInt(string || 0);
}

function fixStr(string) {
    return string || '';
}
function fixNull (string) {
    if (string && string == 'null') {
        return null;
    } else {
       return string;
    }
}


//从大到小排序
function sort(sortord, data) {
    parseStringData(data);
    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data.length - i; j++) {
            if (sortord == 'desc') {
                if (data[j] < data[j + 1]) {
                    for (var k = 1; k < arguments.length; k++) {
                        var temp = arguments[k][j];
                        arguments[k][j] = arguments[k][j + 1];
                        arguments[k][j + 1] = temp;
                    }
                }
            } else {
                if (data[j] > data[j + 1]) {
                    for (var k = 1; k < arguments.length; k++) {
                        var temp = arguments[k][j];
                        arguments[k][j] = arguments[k][j + 1];
                        arguments[k][j + 1] = temp;
                    }
                }
            }
        }
    }
}

//导出Excel
function exportExcel(modal) {
    // 3秒之内无法点击
    loading();
    var _this = $(modal).find('.export_excel');
    _this.off().find('i').removeClass('fa-upload').addClass('fa-hourglass').css('cursor', 'wait');
    setTimeout(function () {
        _this.find('i').removeClass('fa-hourglass').addClass('fa-upload').css('cursor', 'pointer');
        _this.click(exportExcel);
        loading(true);
    }, 3000);
    var table = $(modal).find('table:visible');
    var thead = table.find('thead');
    var tbody = table.find('tbody');
    var tfoot = table.find('tfoot');
    var tr = null;
    /* 获取thead */
    var theadArr = [];
    tr = thead.find('th');
    for (var i = 0; i < tr.length; i++) {
        theadArr.push(tr.eq(i).text());
    }
    /* 获取tbody */
    var tbodyArr = {};
    tr = tbody.find('tr');
    var td = tbody.find('tr td[rowspan]');
    if (td.length) {
        for (var i = 0; i < td.length; i++) {
            var key = td.eq(i).text();
            var index = td.eq(i).parent().index();
            var count = td.eq(i).attr('rowspan');
            var arr = [];
            for (var j = index; j < index + parseInt(count); j++) {
                var arr1 = [];
                var tdEl = tr.eq(j).find('td');
                var start = j === index ? 1 : 0;
                for (var k = start; k < tdEl.length; k++) {
                    arr1.push(tdEl.eq(k).text());
                }
                arr.push(arr1)
            }
            tbodyArr[key] = arr;
        }
    } else {
        var trArr = [];
        for (var i = 0; i < tr.length; i++) {
            var trArrTemp = [];
            for (var j = 0; j < tr.eq(i).children().length; j++) {
                trArrTemp.push(tr.eq(i).children().eq(j).text());
            }
            trArr.push(trArrTemp);
        }
        tbodyArr = {0: trArr};
    }
    /* tfoot */
    var tfootArr = [];
    tr = tfoot.find('td');
    for (var i = 0; i < tr.length; i++) {
        tfootArr.push(tr.eq(i).text());
    }
    /*var tr = table.find('tr');
    var trArr = [];
    var trArrTemp = [];
    for (var i = 0; i < tr.length; i++) {
        if (tr.eq(i).children().length > 1) {
            if (tr.eq(i).parent().parent('table').prop('id').indexOf('detail-table-') == -1) {   // 父表
                trArrTemp = [];
            } else {    // 子表
                trArrTemp = ['', ''];
            }
            for (var j = 0; j < tr.eq(i).children().length; j++) {
                trArrTemp.push(tr.eq(i).children().eq(j).text());
            }
            trArr.push(trArrTemp);
        }
    }
    $('#fileName').val($('#modal').find('.iziModal-header').find('.iziModal-header-title').text());
    $('#tbody').val(JSON.stringify(trArr));
    $('#exportExcel').submit();
    */
    var form = $('#exportExcel');
    if (!form.length) {
        $('body').append('<form action="' + basePath + '/charts/excelexport" method="post" id="exportExcel" style="display:none;">' +
            '            <input type="text" name="fileName" class="fileName">' +
            '            <input type="text" name="thead" class="thead">' +
            '            <input type="text" name="tbody" class="tbody">' +
            '            <input type="text" name="tfoot" class="tfoot">' +
            '        </form>');
        form = $('#exportExcel');
    }
    form.find('.fileName').val($(modal).find('.iziModal-header-title').text() || $(modal).find('.model-title').text());
    form.find('.thead').val(JSON.stringify(theadArr));
    form.find('.tbody').val(JSON.stringify(tbodyArr));
    form.find('.tfoot').val(JSON.stringify(tfootArr));
    form.submit();
}

function flavrShowByTime(msg, urls, color, isHref) {
    new $.flavr({
        content: msg,
        autoclose: true,
        closeOverlay: true,
        closeEsc: true,
        buttons: [{text: 'ok', style: color}],
        timeout: 3500,
        onClose: function () {
            if (isHref && urls != null) {
                window.location.href = urls;
            }
        }
    });
}

// 搜索框对象
var ChooseBox = {
    main: $('.choose'),
    width: lang == 'en' ? 500 : 400,
    status: true,
    run_status: true,
    search_id: {},
    cookie_search: JSON.parse($.cookie('chooseValue') || '{}'),
    init: function () {

    },
    siblingsClick: function () {
        var _this = this;
        this.main.siblings().click(function () {
            _this.close();
        });
        this.clearSearch();
    },
    clearSearch: function () {
        var _this = this;
        if (lang == 'en') {
            this.main.find('th').html('Plug Conditions' + '<button style="font:12px/16px \'\';height:22px;background:#112541;border-radius:4px;outline:0;border:0;color:#fff;" id="clear_search">Empty Plug Selection</button>');
        } else {
            this.main.find('th').html('筛选条件' + '<button style="font:12px/16px \'\';height:22px;background:#112541;border-radius:4px;outline:0;border:0;color:#fff;" id="clear_search">清空筛选</button>');
        }
        $('#clear_search').click(function () {
            $('.select_hospital').val('').trigger('change');
            $('.select_level').val('').select2({
                placeholder: lang == 'zh' ? '请选择' : 'Please Choose',
                allowClear: true
            });
            $('.select_risk').val('').trigger('change');
            $('.select_type').val('').trigger('change');
            $('.select_brand').val('').trigger('change');
            $('.select_year').val('').trigger('change');
            $('.select_month').val('').trigger('change');
            $('#enableYearStart').val('').trigger('change');
            $('#enableYearEnd').val('').trigger('change');
            $('#priceStart').val('').trigger('change');
            $('#priceEnd').val('').trigger('change');
            $('#ageLimitStart').val('').trigger('change');
            $('#ageLimitEnd').val('').trigger('change');
        });
    },
    toggle: function () {
        if (this.status) {
            this.open();
        } else {
            this.close();
        }
    },
    open: function () {
        var _this = this;
        if (this.run_status) {
            this.run_status = false;
            this.main.animate({
                width: this.width,
                height: '100%',
                opacity: 1
            }, 'slow', function () {
                _this.status = false;
                _this.run_status = true;
            });
        }
    },
    close: function () {
        var _this = this;
        if (this.run_status) {
            this.run_status = false;
            this.main.animate({
                width: 0,
                height: 0,
                opacity: 0
            }, 'slow', function () {
                _this.status = true;
                _this.run_status = true;
                $('.select_hospital').val(hospitalId).trigger('change');
                $('.select_level').val() && ($('.select_level').val().join('') != levelId.join('')) ? $('.select_level').val(levelId).trigger('change') : '';
                $('.select_risk').val(riskId).trigger('change');
                $('.select_type').val(typeId).trigger('change');
                $('.select_brand').val(brandId).trigger('change');
                $('.select_year').val(year).trigger('change');
                $('.select_month').val(monthId).trigger('change');
                $('#enableYearStart').val(enableYearStart).trigger('change');
                $('#enableYearEnd').val(enableYearEnd).trigger('change');
                $('#priceStart').val(priceStart ? (priceStart / CONST) : '').trigger('change');
                $('#priceEnd').val(priceEnd ? (priceEnd / CONST) : '').trigger('change');
                $('#ageLimitStart').val(ageLimitStart).trigger('change');
                $('#ageLimitEnd').val(ageLimitEnd).trigger('change');
                $("input[name='limit-range']:checked").parents("div").removeClass("checked");
                $("input[name='limit-range']:checked").removeAttr("checked");
                $("input[name='price']:checked").parents("div").removeClass("checked");
                $("input[name='price']:checked").removeAttr("checked");
                appendTime();
            });
        }
    },
    setSearchToggle: function (domStr, searchName, id) {
        this.search_id[searchName] = this.search_id[searchName] || [];
        if (this.search_id[searchName].hasValue(id)) {
            this.search_id[searchName].removeByValue(id);
        } else {
            this.search_id[searchName].push(id);
        }
        $(domStr).val(this.search_id[searchName]).trigger('change');
        getParams();
    },
    setSearchFromCookie: function (tag) {
        switch (tag) {
            case 'department':
                $('.select_hospital').val(this.cookie_search.hospitalId).trigger('change');
                break;
            case 'hospital':
                $('.select_hospital').val(this.cookie_search.hospitalId).trigger('change');
                break;
            case 'level':
                $('.select_level').val(this.cookie_search.levelId).trigger('change');
                // TOP5的level筛选框
                $('#title_level').on('change', function (param) {
                    levelId = $(this).val() ? [$(this).val()] : '';
                    $('.choose .select_level').val(levelId).trigger('change');
                    getParams();
                }).on("select2:unselecting", function (e) {
                    e.preventDefault();
                    $(this).val('').trigger('change');
                });
                break;
            case 'risk':
                $('.select_risk').val(this.cookie_search.riskId).trigger('change');
                break;
            case 'type':
                $('.select_type').val(this.cookie_search.typeId).trigger('change');
                break;
            case 'brand':
                $('.select_brand').val(this.cookie_search.brandId).trigger('change');
                break;
            case 'year':
                $('.select_year').val(this.cookie_search.year).trigger('change');
                break;
            case 'month':
                $('.select_month').val(this.cookie_search.monthId).trigger('change');
                break;
        }
        $('#enableYearStart').val(this.cookie_search.enableYearStart);
        $('#enableYearEnd').val(this.cookie_search.enableYearEnd);
        this.cookie_search.priceStart ? $('#priceStart').val(this.cookie_search.priceStart / CONST) : '';
        this.cookie_search.priceEnd ? $('#priceEnd').val(this.cookie_search.priceEnd / CONST) : '';
        $('#ageLimitStart').val(this.cookie_search.ageLimitStart);
        $('#ageLimitEnd').val(this.cookie_search.ageLimitEnd);
    }
};

//表格排序
function sortTable(sTableId, iCol, sDataType) {
    var sorts = $('#' + sTableId).find('thead th');
    var img = sorts.eq(iCol).find('img');
    var oTable = document.getElementById(sTableId);//获得表
    var oTBody = oTable.tBodies[0];//获得放数据的body,因为该表格只有一个tbody,所以直接用[0]
    var colRows = oTBody.rows;//获得tbody里所有的tr
    var aTRs = [];//声明一个数组
    for (var i = 0; i < colRows.length; i++) {
        aTRs[i] = colRows[i];//将tr依次放入数组中;
    }
    if (oTable.sortCol === iCol) {
        aTRs.reverse();//如果当前要排的列和上次排的列是一样的,就直接逆向排序;也就是说连着对一列点两次,就会进行升序,降序的转换.
        if (img.attr('src').indexOf('sort_up.png') !== -1) {
            img.attr('src', basePath + '/plugins/charts/images/sort_down.png');
        } else {
            img.attr('src', basePath + '/plugins/charts/images/sort_up.png');
        }
    } else {
        aTRs.sort(getSortFunction(iCol, sDataType));//排序,并且传入一个获得到的比较函数;
        img.attr('src', basePath + '/plugins/charts/images/sort_up.png');
    }
    for (var i = 0; i < sorts.length; i++) {
        if (i === iCol) {
            continue;
        }
        sorts.eq(i).find('img').attr('src', basePath + '/plugins/charts/images/sort.png');
    }
    var oFragement = document.createDocumentFragment();//创建文档碎片,用来存放排好的tr
    for (var i = 0; i < aTRs.length; i++) {
        oFragement.appendChild(aTRs[i]);//将tr绑定到碎片上.
    }
    oTBody.appendChild(oFragement);//将碎片绑定在表格上
    oTable.sortCol = iCol;//记住当前列,这个可以用来判断是对数组进行反向排序还是重新按列排;
}

function getSortFunction(iCol, sDataType) {
    return function compareTRs(oTR1, oTR2) {
        var vValue1, vValue2;
        if (oTR1.cells[iCol].getAttribute("value")) {
            vValue1 = convert(oTR1.cells[iCol].getAttribute("value"), sDataType);
            vValue2 = convert(oTR2.cells[iCol].getAttribute("value"), sDataType);
        } else {
            vValue1 = convert(oTR1.cells[iCol].firstChild ? oTR1.cells[iCol].innerText : 0, sDataType);
            vValue2 = convert(oTR2.cells[iCol].firstChild ? oTR2.cells[iCol].innerText : 0, sDataType);
        }
        if (vValue1 < vValue2) {
            return -1;
        } else if (vValue1 > vValue2) {
            return 1;
        } else {
            return 0;
        }
    }
}

function convert(sValue, sDataType) {
    if (sDataType) {
        switch (sDataType) {
            case "int":
                return parseInt(sValue);
            case "float":
                return parseFloat(sValue);
            case "date":
                return new Date(Date.parse(sValue));
            default:
                return sValue;
        }
    } else {
        return /^[0-9]+(.[0-9]{2})?$/.test(sValue) ? parseFloat(sValue) : sValue;
    }
}

$("#modal").length > 0 ? $("#modal, #typeModal").each(function () {
    var obj = this;
    $(obj).iziModal({
        title: 'title',
        headerColor: '#222431',
        width: '100%',
        radius: 3,
        zindex: $(obj).attr('id') === 'modal' ? 1040 : 1090,
        navigateCaption: true,
        navigateArrows: true, // closeToModal, closeScreenEdge
        history: false,
        restoreDefaultContent: false,
        autoOpen: false, // Boolean, Number
        bodyOverflow: true,
        fullscreen: true,
        overlayColor: 'rgba(0, 0, 0, 0)',
        transitionIn: 'comingIn',
        transitionOut: 'comingOut',
        transitionInOverlay: 'fadeIn',
        transitionOutOverlay: 'fadeOut',
        onOpening: function () {
            $(obj).find('.iziModal-header').append('<a class="iziModal-button export_excel" href="javascript:void(0);" onclick="exportExcel(\'#'+$(obj).attr('id')+'\')" title="导出"><i class="fa fa-upload"></i></a>');
            $(obj).find('.box-body').height($(obj).height() - 44);
        },
        onClosed: function () {
            if ($(obj).attr('id') === 'modal') {
                $(obj).find('table').html('<tbody id="table_data"></tbody>');
            } else if ($(obj).attr('id') === 'typeModal') {
                $(obj).find('table').html('<tbody></tbody>');
            }
        }
    });
}) : null;

function flavrShowByTime(msg, urls, color, isHref) {
    if (!msg || msg === '该用户不存在') {
        return;
    }
    new $.flavr({
        content: msg,
        autoclose: true,
        closeOverlay: true,
        closeEsc: true,
        buttons: [{text: 'ok', style: color}],
        timeout: 3500,
        onClose: function () {
            if (isHref && urls != null) {
                window.location.href = urls;
            }
        }
    });
}


/*
* 点击跳转页面
* 根据class为page的span元素的自定义属性page的值跳转页面
* <span class="page" page="hospital-index"></span>
* 点击此span元素会跳转到<%=basePath%>/charts/area/hospital-index/page页面
* */
$('.page').on('click', (function () {
    if ($(this).attr('page')) {
        location.href = basePath + '/charts/area/' + $(this).attr('page') + '/page?hospitalId=' + hspId;
    } else {
        location.href = basePath + '/charts/hospital/' + $(this).attr('page-hospital') + '/page?hospitalId=' + hspId;
    }

}));

/*
    使用规则：
    1.使用该方法，需要计算的td的类名必须包含total-或者average-，且类名不能重复
    2.不需要计算的则加上no-cal类。
    3.将total-,average-,no-cal这些类名放在最前面
    4.该表必须要有tbody元素
    5.sortStatus表示表格是否排序
*/
function calTableData(tableId, sortStatus, dealBtn) {
    var isType = false;
    var thHasVal = false;
    var param = {};
    dealBtn = dealBtn || '';
    if (typeof tableId === 'object') {
        isType = tableId.isType;
        param = tableId.param || {};
        tableId = tableId.tableId;
    }
    addArrowYoy('#' + tableId); //添加同比箭头
    var table = $("#" + tableId);
    var ths = table.find('thead th').each(function(){
        var obj = $(this);
        if (obj.attr('value')) {
            thHasVal = true;
            return;
        }
    });
    var countTbody = table.find('tbody').eq(0);
    var firstTypeCount = countTbody.children('tr[class="border-bottom"]').length;
    var hasClassCount = countTbody.children('tr[class]').length;
    var totalCount = countTbody.children('tr').length;
    var countTotal = totalCount - hasClassCount;
    if (thHasVal) {
        var str = '';
        for (var i = 0; i < ths.length; i++) {
            str += '<td class="' + ths.eq(i).attr('class') + '">' + (ths.eq(i).attr('value') || '') + '</td>'
        }

        if (table.find('tfoot').length) {
            table.find('tfoot').html("<tr>" + str + "</tr>");
        } else {
            table.append("<tfoot><tr>" + str + "</tr></tfoot>");
        }
        var tfoot = table.find('tfoot td');
        tfoot.eq(0).html(tfoot.eq(0).html() + ' ' + (firstTypeCount || ''));
        tfoot.eq(1).html(tfoot.eq(1).html() + ' ' + (countTotal || ''));
    } else {
        var countClassArr = [];//用来存放要计算列的类名
        var amountArr = [];
        $("#" + tableId + " tbody tr:first td").each(function () {
            if ($(this)[0].className.indexOf("no-cal") === -1) {//如果该列含有no-cal则表示不需要计算
                var totalNum = $(this)[0].className.split(" ")[0];//获取要计算的列的class name
                countClassArr.push(totalNum);
            } else {
                countClassArr.push('no-cal');
            }
        });
        for (var x = 2; x < countClassArr.length; x++) {
            var num = 0;
            if (countClassArr[x] != 'no-cal') {
                $("#" + tableId + " ." + countClassArr[x]).each(function () {
                    num = num + parseFloat($(this)[0].innerText || 0);
                });
            }

            if (countClassArr[x].indexOf("total") != -1) {//如果是带有total的类名则算总值
                if (/\./.test(num)) {
                    amountArr.push(fix2(num));
                } else {
                    amountArr.push(num);
                }
            } else if (countClassArr[x].indexOf("no-cal") != -1) {
                amountArr.push(null);
            } else {//否则计算平均值
                amountArr.push(fix2(num / $("#" + tableId + " ." + countClassArr[x]).length));
            }
        }
        appendStr = '';
        for (var x = 0; x < amountArr.length; x++) {
            appendStr += "<td class='text-right'>" + (amountArr[x] == null ? '' : amountArr[x]) + "</td>"
        }
        if (table.find('tfoot').length) {
            table.find('tfoot').html("<tr><td class='text-center'>" + (lang === 'en' ? 'Total' : '总计') + dealBtn + ' ' + (firstTypeCount || '') + "</td><td>"+countTotal+"</td>" + appendStr + "</tr>");
        } else {
            table.append("<tfoot><tr><td class='text-center'>" + (lang === 'en' ? 'Total' : '总计') + dealBtn + ' ' + (firstTypeCount || '') + "</td><td>"+countTotal+"</td>" + appendStr + "</tr></tfoot>");
        }
    }


    /* 点击标题排序 */
    if (sortStatus) {
        $('#' + tableId).find('th').each(function () {
            var obj = $(this);
            var img = obj.find('img');
            img.length ? img.attr('src', basePath + '/plugins/charts/images/sort.png') : obj.append('<img src="' + basePath + '/plugins/charts/images/sort.png' + '">');
            img = obj.find('img');
            obj.click(function () {
                var index = obj.index();
                if (isType) {
                    if (img.attr('src').indexOf('sort_down.png') > -1) {
                        param.dataJson.sortByKey('asc', obj.attr('key'));
                        moretypes($.extend({}, {
                            id: '',
                            dataJson: typeJson,
                            modal: 'modal',
                            table: 'tblSort'
                        }, param));
                        $('#' + tableId).find('th').eq(index).find('img').attr('src', basePath + '/plugins/charts/images/sort_up.png');
                    } else {
                        param.dataJson.sortByKey(obj.attr('key'));
                        moretypes($.extend({}, {
                            id: '',
                            dataJson: typeJson,
                            modal: 'modal',
                            table: 'tblSort'
                        }, param));
                        $('#' + tableId).find('th').eq(index).find('img').attr('src', basePath + '/plugins/charts/images/sort_down.png');
                    }
                } else {
                    sortTable(tableId, index, false);
                }
            })
        });
    }

    if (countTotal > 200) {
        table.tableHeadFixer({'head': true, 'foot': true});
    } else {
        table.tableHeadFixer({'left': 2, 'head': true, 'foot': true});
    }
}


/*
 * 象限
  * */
var currentOptionTemp;
$('.quadrant').click(function () {
    var index = $(this).index();
    var arr = optionAgelimit.series[0].data;
    var markLimeArr = optionAgelimit.series[0].markLine.data;
    var arrTemp = [];
    currentOptionTemp = optionAgelimit;
    if ($(this).hasClass('active')) {
        arrTemp = arr;
        currentOptionTemp.series[0].markLine.data = markLimeArr;
    } else if (index === 1) {
        for (var i = 0; i < arr.length; i++) {
            if ((parseFloat(arr[i][0]) >= parseFloat(markLimeArr[0].xAxis)) && (parseFloat(arr[i][1]) >= parseFloat(markLimeArr[1].yAxis))) {
                arrTemp.push(arr[i]);
            } else {
                arrTemp.push([0, 0, 0, i])
            }
        }
        currentOptionTemp.series[0].markLine.data = [];
    } else if (index === 2) {
        for (var i = 0; i < arr.length; i++) {
            if ((parseFloat(arr[i][0]) < parseFloat(markLimeArr[0].xAxis)) && (parseFloat(arr[i][1]) >= parseFloat(markLimeArr[1].yAxis))) {
                arrTemp.push(arr[i]);
            } else {
                arrTemp.push([0, 0, 0, i])
            }
        }
        currentOptionTemp.series[0].markLine.data = [];
    } else if (index === 3) {
        for (var i = 0; i < arr.length; i++) {
            if ((parseFloat(arr[i][0]) < parseFloat(markLimeArr[0].xAxis)) && (parseFloat(arr[i][1]) < parseFloat(markLimeArr[1].yAxis))) {
                arrTemp.push(arr[i]);
            } else {
                arrTemp.push([0, 0, 0, i])
            }
        }
        currentOptionTemp.series[0].markLine.data = [];
    } else if (index === 4) {
        for (var i = 0; i < arr.length; i++) {
            if ((parseFloat(arr[i][0]) >= parseFloat(markLimeArr[0].xAxis)) && (parseFloat(arr[i][1]) < parseFloat(markLimeArr[1].yAxis))) {
                arrTemp.push(arr[i]);
            } else {
                arrTemp.push([0, 0, 0, i])
            }
        }
        currentOptionTemp.series[0].markLine.data = [];
    }
    currentOptionTemp.series[0].data = arrTemp;
    chart.clear();
    chart.setOption(currentOptionTemp);
    optionAgelimit.series[0].data = arr;
    optionAgelimit.series[0].markLine.data = markLimeArr;
});

//截至时间 和 医院
var $appendTime_status = true;
var $_department_id_name = {};
var $_type_id_name = {};
var $_time = '';

function appendTime() {
    var $_department = '';
    var $_type = '';
    if ($appendTime_status) {
        $.ajax({
            type: "POST",
            data: {
              hospitalId: hspId
            },
            url: basePath + ($('.select_level').length > 0 ? '/area/search/time' : '/hospital/search/time'),
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.ret === 1) {
                    $_time = lang == 'en' ? (data.data.enTime || '') : (data.data.time || '');
                } else {
                    flavrShowByTime(data.msg, null, "danger", false);
                }
            },
            failure: function () {
                flavrShowByTime(data.msg, null, "danger", false);
            }
        });
        $.ajax({
            type: "POST",
            data: {
              hospitalId: hspId
            },
            url: basePath + ($('.select_level').length > 0 ? '/area/search/hospital' : '/hospital/search/department'),
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.ret === 1) {
                    for (var i = 0; i < data.data.list.length; i++) {
                        $_department_id_name[data.data.list[i].id] = data.data.list[i].name;
                    }
                } else {
                    flavrShowByTime(data.msg, null, "danger", false);
                }
            },
            failure: function () {
                flavrShowByTime(data.msg, null, "danger", false);
            }
        });
        $.ajax({
            type: "POST",
            data: {
              hospitalId: hspId
            },
            url: basePath + ($('.select_level').length > 0 ? '/area/search/type' : '/hospital/search/type'),
            dataType: "json",
            async: false,
            success: function (data) {
                if (data.ret === 1) {
                    for (var key in data.data) {
                        for (var i = 0; i < data.data[key].length; i++) {
                            $_type_id_name[data.data[key][i].id] = data.data[key][i].name;
                        }
                    }
                } else {
                    flavrShowByTime(data.msg, null, "danger", false);
                }
            },
            failure: function () {
                flavrShowByTime(data.msg, null, "danger", false);
            }
        });
    }
    var $_department_id = $('.select_hospital').val() || [];
    var $_type_id = $('.select_type').val() || [];
    for (var i = 0; i < $_department_id.length; i++) {
        $_department += ((i == 0 ? '' : ',') + '<span>' + $_department_id_name[$_department_id[i]]).split('[')[0] + '<span onclick="resetSearch(\'hospital\')">×</span></span>';
    }
    for (var i = 0; i < $_type_id.length; i++) {
        $_type += ((i == 0 ? '' : ',') + '<span>' + $_type_id_name[$_type_id[i]]).split('[')[0] + '<span onclick="resetSearch(\'type\')">×</span></span>';
    }
    if ($appendTime_status) {
        $('.global_area').prepend('<div class="fr">' +
            '<p class="tr time">' + (lang == 'en' ? 'Closing Date' : '截至日期') + '：' + $_time + '</p>' +
            '<p class="tr department">' + $_department + '</p>' +
            '</div>');
        $('#top5_type').find('p.title').append('<span class="type" style="margin-left:5px;">' + $_type + '</span>');
        $appendTime_status = false;
    } else {
        $('.time').html((lang == 'en' ? 'Closing Date' : '截至日期') + '：' + $_time);
        $('.department').html($_department);
        $('.type').html($_type);
    }
}

function resetSearch(tag) {
    $('.select_' + tag).val('').trigger('change');
    getParams();
}

// 处理排名右侧滚动条和area高度
function resizeWindow() {
    $('.bottom_bar').height($('.bottom_bar').height());
    $('.chart-border .area').css('height', $('.chart-border').height());
    var userAgentInfo = navigator.userAgent;
    var Agents = ["iPad"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    if (flag) {
        $('.data_detail').css('paddingRight', '0');
    } else {
        $('.data_detail').css('paddingRight', '18px');
    }

    if ($('body').width() < 1024) {
        $('.chart-border').height($(this).width() * 0.8);
    }
    var height = $('.list_data .border').height();
    $('.list_data .border .area').height(height);
}

// 重置按钮，清空搜索条件cookie和搜索条件
function reset() {
    $.cookie('chooseValue', '{}', {path: '/'});
    location.reload();
}
/* 退出登录 */
function logout() {
    $.cookie('chooseValue', '{}', {path: '/'});
    location.href = basePath + '/logout';
}

function addChooseRadioEvent(tag) {
    setDefaultPrice(tag);
    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-blue',
        radioClass: 'iradio_flat-blue'
    });
    $("input[type='radio'][name='limit-range']").on('ifChecked', function (event) {
        var range = $("input[name='limit-range']:checked").val();
        if (range == 1) {
            $("#ageLimitStart").val(0.0);
            $("#ageLimitEnd").val(0.5);
        } else if (range == 2) {
            $("#ageLimitStart").val(0.5);
            $("#ageLimitEnd").val(1.0);
        } else {
            $("#ageLimitStart").val(1.0);
            $("#ageLimitEnd").val(1.5);
        }
    });
    $("input[type='radio'][name='price']").on('ifChecked', function (event) {
        var range = $("input[name='price']:checked").val();
        if (range == 1) {
            $("#priceStart").val('');
            $("#priceEnd").val(priceStartVal);
        } else if (range == 2) {
            $("#priceStart").val(priceStartVal);
            $("#priceEnd").val(priceEndVal);
        } else {
            $("#priceStart").val(priceEndVal);
            $("#priceEnd").val('');
        }
    });
    //当年限指数输入的范围不是radio上面的范围时，radio取消选中
    $("#ageLimitStart,#ageLimitEnd").blur(function () {
        var b1 = $("#ageLimitStart").val() == 0 && $("#ageLimitEnd").val() == 0.5;
        var b2 = $("#ageLimitStart").val() == 0.5 && $("#ageLimitEnd").val() == 1;
        var b3 = $("#ageLimitStart").val() == 1 && $("#ageLimitEnd").val() == 1.5;
        if (!(b1 || b2 || b3)) {
            $("input[name='limit-range']:checked").parents("div").removeClass("checked");
            $("input[name='limit-range']:checked").removeAttr("checked");
        } else {
            if (b1) {
                $("input[name='limit-range'][value='1']").parents("div").addClass("checked");
                $("input[name='limit-range'][value='1']").prop("checked", "checked");
            } else if (b2) {
                $("input[name='limit-range'][value='2']").parents("div").addClass("checked");
                $("input[name='limit-range'][value='2']").prop("checked", "checked");
            } else {
                $("input[name='limit-range'][value='3']").parents("div").addClass("checked");
                $("input[name='limit-range'][value='3']").prop("checked", "checked");
            }
        }
    });
    $("#priceStart,#priceEnd").blur(function () {
        var b1 = $("#priceStart").val() == '' && $("#priceEnd").val() == priceStartVal;
        var b2 = $("#priceStart").val() == priceStartVal && $("#priceEnd").val() == priceEndVal;
        var b3 = $("#priceStart").val() == priceEndVal && $("#priceEnd").val() == '';
        if (!(b1 || b2 || b3)) {
            $("input[name='price']:checked").parents("div").removeClass("checked");
            $("input[name='price']:checked").removeAttr("checked");
        } else {
            if (b1) {
                $("input[name='price'][value='1']").parents("div").addClass("checked");
                $("input[name='price'][value='1']").prop("checked", "checked");
            } else if (b2) {
                $("input[name='price'][value='2']").parents("div").addClass("checked");
                $("input[name='price'][value='2']").prop("checked", "checked");
            } else {
                $("input[name='price'][value='3']").parents("div").addClass("checked");
                $("input[name='price'][value='3']").prop("checked", "checked");
            }
        }
    });
}

/*
* Top5显示、隐藏-年限、月份
* false-不显示年份、月份TOP5
* true-显示年份、月份TOP5
* */
function showYearTop5(status) {
    if (status) { // 显示年份、月份TOP5
        $('.top5').hide();
        $('#top5_device').show();
        $('#top5_year').show();
    } else { // 不显示年份、月份TOP5
        $('.top5').show();
        $('#top5_year').hide();
    }

}

/*
* 根据参数名获取url中的参数
* name  参数名
* */
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

/*
* 给指定父元素下的.yoy元素加上箭头
* parent为父元素选择器
* */
function addArrowYoy(parent) {
    if (parent) {
        $(parent + ' .yoy').each(function () {
            var val = parseFloat($(this).text());
            if (val > 0) {
                $(this).append('<img src="' + basePath + '/plugins/charts/images/arrow_up.png" style="height:1.2em;vertical-align: middle;margin-top: -0.04rem;"/>');
            } else if (val < 0) {
                $(this).append('<img src="' + basePath + '/plugins/charts/images/arrow_down.png" style="height:1.2em;vertical-align: middle;margin-top: -0.04rem;"/>');
            } else {
                $(this).append('<img src="' + basePath + '/plugins/charts/images/arrow_zero.png" style="height:1.2em;vertical-align: middle;margin-top: -0.04rem;"/>');
            }
        });
    }
}

/*
* 设置默认金额
* */
var priceStartVal, priceEndVal;

function setDefaultPrice(tag) {
    $.ajax({
        type: "POST",
          data: {
            hospitalId: hspId
          },
        url: basePath + "/" + tag + "/search/price",
        async: false,
        dataType: "json",
        success: function (data) {
            if (data.ret) {
                $('#priceStart').val(data.data.list[0].name);
                priceEndVal = data.data.list[1].name;
                priceStartVal = data.data.list[2].name;

                $('#priceStart').parent('td').parent('tr').after('<tr>' +
                    '                <td class="tr"></td>' +
                    '                <td class="tl">' +
                    '                    <label style="margin-right: 10px">' +
                    '                        <input type="radio" class="flat-green" value="1" name="price">' +
                    '                        <span>&lt;' + priceStartVal + '</span>' +
                    '                    </label>' +
                    '                    <label style="margin-right: 10px">' +
                    '                        <input type="radio" class="flat-green"  value="2" name="price">' +
                    '                        <span>' + priceStartVal + '-' + priceEndVal + '</span>' +
                    '                    </label>' +
                    '                    <label>' +
                    '                        <input type="radio" class="flat-green" value="3" name="price">' +
                    '                        <span>&gt;' + priceEndVal + '</span>' +
                    '                    </label>' +
                    '                </td>' +
                    '            </tr>');
            } else {
                flavrShowByTime(data.msg, null, "danger", false);
            }
        },
        failure: function (data) {
            flavrShowByTime(data.msg, null, "danger", false);
        }
    });
}

/*
* Loading动画
* */
function loading(isOver, time) {
    var loadingDiv = $('#loading-div');
    if (isOver === true) {
        loadingDiv.hide();
    } else {
        if (loadingDiv.length) {
            loadingDiv.show();
        } else {
            $('body').append('<div id="loading-div" style="display: none;"><img src="' + basePath + '/public/images/loading.gif" alt="正在加载，请稍候……"></div>').append('<style>#loading-div {position: fixed;width: 100%;height: 100%;left: 0;top: 0;background: rgba(0,0,0,0.5);z-index: 99999;}#loading-div img {display: block;width: 4rem;height: 4rem;position: absolute;left: 50%;top: 50%;margin: -2rem 0 0 -2rem;}</style>');
            $('#loading-div').show();
        }
    }
    if (typeof isOver === 'function') setTimeout(isOver, time || 5);
}

function basePath() {
    //获取当前网址，如： http://localhost:8080/ems/Pages/Basic/Person.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： /ems/Pages/Basic/Person.jsp
    var pathName = window.document.location.pathname;
    var pos = pathName === "/" ? (curWwwPath.length - 1) : curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8080
    var localhostPath = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/ems
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    //获取项目的basePath   http://localhost:8080/ems/
    var basePath = localhostPath + projectName + "/";
    return basePath;
}

/*公共的ajax请求。
url:不带basePath全路径，
项目上下文是basePath，
 type:请求方式,通常是post请求,
 parameter:参数 ，json类型
 fn回调，将返回结果交给调用方处理
 */
function publicAjax(url, type, parameter, fn, isLoading, jsonp, param) {
    param = $.extend({
        async: true
    }, param);
    if (typeof fn != 'function') {
        flavrShowByTime("回调必须是个函数,function", null, "danger", false);
        return;
    }
    isLoading ? null : loading();
    /* 是否反响代理 */
    var jsonpPram = jsonp ? {dataType: "jsonp",jsonp: "callbackfn",jsonpCallback:'callbackfn'} : {};
    $.ajax($.extend({
        url: url,
        type: type,
        async: param.async,
        data: parameter || {},
        success: function (data) {
            if (data.ret === undefined){
                location.href = basePath;
            }
            fn(data);
            if (data.ret == 500) {
                // refreshRightDiv("error-500.html",null,2);
                console.log("出错额。。。。500")
            } else if (data.ret == 404) {
                refreshRightDiv("error-404.html", null, 2);
                console.log("出错额。。。。404")
            }
            isLoading ? null : loading(true);
        },
        callbackfn: function (data){
            if (data.ret === undefined){
                location.href = basePath;
            }
            fn(data);
            if (data.ret == 500) {
                // refreshRightDiv("error-500.html",null,2);
                console.log("出错额。。。。500")
            } else if (data.ret == 404) {
                refreshRightDiv("error-404.html", null, 2);
                console.log("出错额。。。。404")
            }
            isLoading ? null : loading(true);
        },
        error: function (data) {
            if (data.status == 404) {
                console.log(data);
            } else if (!data.ret){
                location.href = basePath;
            }
            isLoading ? null : loading(true);
            console.log("出错la。。。。");
            console.log(data.status);
        }
    }, jsonpPram));
}

/*
* 获取随机数
* */
function getRandom(min, max, type) {
    var num = Math.random() * (max - min + 1) + min;
    if (type === 'int') {
        return parseInt(num);
    } else {
        return num;
    }
}


/*
* 字符串转JSON
* {year:2015,type:154}
* */
function string2json(str) {
    var json = {};
    var strArr = str.slice(1, -1).split(',');
    for (var i = 0; i < strArr.length; i++) {
        json[strArr[i].split(':')[0]] = strArr[i].split(':')[1]
    }
    return json;
}

/*
* 查询新增报废设备详情
* param传参
* */
function queryAssets(param) {
    publicAjax(basePath + '/charts/hospital/department-index/new-or-scrap', 'post', $.extend({}, {
        hospitalId: hspId,
        departmentId: hospitalId ? JSON.stringify(hospitalId) : '',
        riskId: riskId ? JSON.stringify(riskId) : '',
        typeId: typeId ? JSON.stringify(typeId) : '',
        brandId: brandId ? JSON.stringify(brandId) : '',
        year: year ? JSON.stringify(year) : '',
        monthId: monthId ? JSON.stringify(monthId) : '',
        enableYearStart: enableYearStart,
        enableYearEnd: enableYearEnd,
        priceStart: priceStart,
        priceEnd: priceEnd,
        ageLimitStart: ageLimitStart,
        ageLimitEnd: ageLimitEnd
    }, param), function (data) {
        if (data.ret && data.data && data.data.list) {
            var list = data.data.list;
            if (!$('#assetModal').length) {
                $('body').append('<div id="assetModal" class="modal" style="padding-top: 58px;height: 100%;box-sizing: border-box;display: none;">' +
                    '<div class="box-body no-padding">' +
                    '   <table id="assetTable" class="table table-bordered table-striped table-hover table-responsive">' +
                    '       <thead></thead>' +
                    '       <tbody id="asset_data"></tbody>' +
                    '   </table>' +
                    '</div></div>');
                $("#assetModal").iziModal({
                    title: param.assetsTag == 1 ? '新增设备详情' : param.assetsTag == 2 ? '报废设备详情' : '设备详情',
                    headerColor: '#222431',
                    width: '100%',
                    radius: 3,
                    zindex: 1090,
                    navigateCaption: true,
                    navigateArrows: true, // closeToModal, closeScreenEdge
                    history: false,
                    restoreDefaultContent: false,
                    autoOpen: false, // Boolean, Number
                    bodyOverflow: true,
                    fullscreen: true,
                    overlayColor: 'rgba(0, 0, 0, 0)',
                    transitionIn: 'comingIn',
                    transitionOut: 'comingOut',
                    transitionInOverlay: 'fadeIn',
                    transitionOutOverlay: 'fadeOut',
                    onOpening: function () {
                        $('#assetModal').find('.iziModal-header').append('<a class="iziModal-button export_excel" href="javascript:void(0);" onclick="exportExcel(\'#assetModal\')" title="导出"><i class="fa fa-upload"></i></a>');
                        $('#assetModal .box-body').height($('#assetModal').height() - 44);
                    },
                    onClosed: function () {
                        clearTable($('#assetTable'));
                    }
                });
            } else {
                $('#assetModal').iziModal('setTitle', param.assetsTag == 1 ? '新增设备详情' : param.assetsTag == 2 ? '报废设备详情' : '设备详情');
            }
            $('#assetModal').find('thead').html('<th class="text-center">#</th>' +
                '<th class="text-left">设备名称</th>' +
                '<th class="text-left">型号</th>' +
                '<th class="text-left">设备类型</th>' +
                '<th class="text-left">SN编号</th>' +
                '<th class="text-left">资产编号</th>' +
                '<th class="text-left">所属科室</th>' +
                '<th class="text-right">设备金额(万元)</th>' +
                '<th class="text-right">折旧金额(万元)</th>' +
                '<th class="text-right">年限指数</th>' +
                '<th class="text-left">生产厂家</th>' +
                '<th class="text-left">启用日期</th>' +
                '<th class="text-left">报废日期</th>' +
                '<th class="text-right">使用年份</th>');
            var str = '';
            for (var i = 0; i < list.length; i++) {
                str += "<tr>"
                    + "<td class='no-cal text-center'>" + (i + 1) + "</td>"
                    + "<td class='no-cal text-left spanTitle' onclick=\"query('device','" + list[i].id + "')\">" + list[i].name + "</td>"
                    + "<td class='no-cal text-left'>" + (list[i].modalName || '') + "</td>"
                    + "<td class='no-cal'>" + fixStr(list[i].firstTypeName) + "</td>"
                    + "<td class='no-cal text-left'>" + (list[i].sn || '') + "</td>"
                    + "<td class='no-cal text-left'>" + (list[i].assetsNo || '') + "</td>"
                    + "<td class='no-cal text-left'>" + (list[i].department || '') + "</td>"
                    + "<td class='total-1 text-right'>" + parseFloat(list[i].price / CONST || 0).toFixed(2) + "</td>"
                    + "<td class='total-2 text-right'>" + parseFloat(list[i].depreciationPrice / CONST || 0).toFixed(2) + "</td>"
                    + "<td class='avg-1 text-right'>" + parseFloat(list[i].ageLimitMeasure || 0).toFixed(2) + "</td>"
                    + "<td class='no-cal text-left'>" + (list[i].manufacturer || '') + "</td>"
                    + "<td class='no-cal text-left'>" + (list[i].enableDate || '') + "</td>"
                    + "<td class='no-cal text-left'>" + (list[i].scrapTime || '') + "</td>"
                    + "<td class='avg-2 text-right'>" + parseFloat(list[i].usedTime).toFixed(2) + "</td>"
                    + "</tr>";
            }
            $('#asset_data').html(str).siblings('tfoot').empty();
            calTableData('assetTable', true);
            $("#assetModal").iziModal('open');
        }
    });
}

/*
* 添加assetModal模态框
* */
function addAssetModal(title, thead, tbody, tfoot) {
    var modal = $('#assetModal');
    if (!modal.length) {
        $('body').append('<div id="assetModal" class="modal" style="padding-top: 58px;height: 100%;box-sizing: border-box;display: none;">' +
            '<div class="box-body no-padding">' +
            '   <table id="assetTable" class="table table-bordered table-striped table-hover table-responsive">' +
            (thead ? '<thead>' + thead + '</thead>' : '') +
            (tbody ? '<tbody id="asset_data">' + tbody + '</tbody>' : '') +
            (tfoot ? '<tfoot>' + tfoot + '</tfoot>' : '') +
            '   </table>' +
            '</div></div>');
        modal = $('#assetModal');
        modal.iziModal({
            title: title || '',
            headerColor: '#222431',
            width: '100%',
            radius: 3,
            zindex: 1090,
            navigateCaption: true,
            navigateArrows: true, // closeToModal, closeScreenEdge
            history: false,
            restoreDefaultContent: false,
            autoOpen: false, // Boolean, Number
            bodyOverflow: true,
            fullscreen: true,
            overlayColor: 'rgba(0, 0, 0, 0)',
            transitionIn: 'comingIn',
            transitionOut: 'comingOut',
            transitionInOverlay: 'fadeIn',
            transitionOutOverlay: 'fadeOut',
            onOpening: function () {
                modal.find('.iziModal-header').append('<a class="iziModal-button export_excel" href="javascript:void(0);" onclick="exportExcel(\'#assetModal\')" title="导出"><i class="fa fa-upload"></i></a>');
                modal.find('.box-body').height($('#assetModal').height() - 44);
            },
            onClosed: function () {
                clearTable($('#assetTable'));
            }


        });
    } else {
        modal.iziModal('setTitle', title || '');
        var theadEL = modal.find('thead');
        var tbodyEL = modal.find('tbody');
        var tfootEL = modal.find('tfoot');
        var table = $('#assetTable');
        thead ? theadEL.length ? theadEL.html(thead) : table.prepend('<thead></thead>').html(thead) : null;
        tbody ? tbodyEL.length ? tbodyEL.html(tbody) : tbodyEL.length ? tbodyEL.next('<tbody id="asset_data"></tbody>').html(tbody) : table.prepend('<tbody id="asset_data"></tbody>').html(tbody) : null;
        tfoot ? tfootEL.length ? tfootEL.html(tfoot) : table.append('<tfoot></tfoot>').html(tfoot) : null;
    }
    calTableData('assetTable', true);
    modal.iziModal('open');
}

/*
* 详情List分批延时加载
* */
function groupLoading(len, fn) {
    var groupSize = 100;
    fn(0, (len < groupSize ? len : groupSize));
    var count = 1;
    var timer = setInterval(function () {
        if (len > groupSize * count) {
            fn(groupSize * (count++), (groupSize * count > len ? len : groupSize * count));
        } else {
            clearInterval(timer);
        }
    }, 20);
}

/* 清空表格 */
function clearTable (table) {
    table.find('thead').empty();
    table.find('tbody').empty();
    table.find('tfoot').empty();
}

/* 获取日期 */
function getDate() {
    var date = new Date();
    return {
        date: date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日',
        week: function () {
            switch (date.getDay()) {
                case 0 :
                    return '星期日';
                case 1 :
                    return '星期一';
                case 2 :
                    return '星期二';
                case 3 :
                    return '星期三';
                case 4 :
                    return '星期四';
                case 5 :
                    return '星期五';
                case 6 :
                    return '星期六';
                default:
                    return '';
            }
        }
    }
}

/* 获取天气 */
function getWeatherImg(weather) {
    var name = '';
    if (weather.indexOf('沙') !== -1) {
        name = 'sand';
    } else if (weather.indexOf('雪') !== -1) {
        name = 'snow';
    } else if (weather.indexOf('雷') !== -1) {
        name = 'thunder';
    } else if (weather.indexOf('雨') !== -1) {
        name = 'rain';
    } else if (weather.indexOf('雾') !== -1) {
        name = 'flog';
    } else if (weather.indexOf('阴') !== -1) {
        name = 'overcast';
    } else if (weather.indexOf('多云') !== -1) {
        name = 'cloudy';
    } else {
        name = 'sun';
    }
    return '<img src="' + basePath + '/plugins/charts/images/weather/' + name + '.png">';
}

/* 待办事项批量处理 */
function dealBatchDeal() {
    loading();
    setTimeout(function() {
        loading(true);
    }, 500);
    var index = batchDealArr.index = (typeof batchDealArr.index === 'number' ? batchDealArr.index : -1) + 1;
    if (batchDealArr.index < batchDealArr.length) {
        score(batchDealArr[index][0], batchDealArr[index][1], batchDealArr[index][2], batchDealArr[index][3], batchDealArr[index][4], batchDealArr[index][5], true);
    } else {
        batchDealArr.index = batchDealArr.length - 1;
        $('.score').each(function () {
            $(this).iziModal('close');
        });
    }
}
